import axios, {
  type AxiosInstance,
  type Method,
  type ResponseType,
  type InternalAxiosRequestConfig,
  type AxiosResponse,
  type AxiosError,
  type AxiosRequestConfig,
} from "axios";
import { ElMessage } from "element-plus";
import router from "~/router";
import { useUser } from "@/store/modules/user";

const baseURL: string = import.meta.env.VITE_BASE_API;
const request: AxiosInstance = axios.create({
  baseURL,
  method: "GET" as Method,
  headers: { "X-Requested-With": "XMLHttpRequest" },
  responseType: "json" as ResponseType,
});
// 请求拦截
request.interceptors.request.use(
  (
    config: InternalAxiosRequestConfig<any>
  ): InternalAxiosRequestConfig<any> => {
    // if (userStore.getToken) config.headers['token'] = userStore.getToken;
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    const userStore = useUser();
    const token = userStore.get.token;
    if (token !== null) config.headers.Authorization = token;
    return config;
  },
  async (error: AxiosError) => {
    return await Promise.reject(error);
  }
);
// 相应拦截
request.interceptors.response.use(
  (response: AxiosResponse): any => {
    return response;
  },
  async (error: AxiosError) => {
    const { response } = error;
    if (response?.status === 401) {
      if ((response as any).data.data !== undefined) {
        ElMessage.error((response as any).data.data);
      } else {
        ElMessage.error((response as any).data.message);
      }
      const userStore = useUser();
      userStore.setToken(null);
      userStore.setUserInfo({});
      void router.replace("/login");
    }
    return await Promise.reject(error);
  }
);
export { request };
export default <T = any>(config: AxiosRequestConfig): any => {
  return request(config).then((res): any => {
    if (res.config.responseType === "blob") {
      return res.data
    } else if (res.data.code === 200) {
      if (res.data.data !== undefined) {
        return res.data.data as T;
      } else {
        return res.data as T;
      }
    } else {
      return Promise.reject(res.data);
    }
  });
};
